# coding=utf-8
import xml.etree.ElementTree as ET
import re

# 定义一个类，来返回结果
class Result(object):
    pass


def load_xml(result_source_xml, result_set_configuration_file_url, btype_id):
    root = ET.fromstring(result_source_xml)
    return parse_to_result(root, result_set_configuration_file_url, btype_id)


def parse_to_result(result_source_root, result_set_configuration_file_url, btype_id):
    results = []
    try:
        result_set_root = ET.fromstring(open(result_set_configuration_file_url).read())
    except IOError as e:
        print("Cloud not open and read file from url: %s" % result_set_configuration_file_url)
        print(e.message)
        raise
    matched_node = filter(lambda ele: ele.attrib['id'] == btype_id, result_set_root.getchildren())
    if len(matched_node) == 0:
        raise Exception('没有找到与ID:%s 相关的xml配置，请检查ResultDataSetConfiguration.xml的ResultSet的id属性是否配置正确' % btype_id)
    if len(matched_node) > 1:
        raise Exception('找到多个与ID:%s 相关的xml配置，请检查ResultDataSetConfiguration.xml的ResultSet的id属性是否配置正确' % btype_id)
    index = 0
    for node in matched_node[0]._children:
        # 先用namespace去找，因为电信返回的接口很多情况下root里面一层都有namespace的
        source_node = result_source_root.find(
            node.attrib['namespace'] if node.attrib['namespace'] != '' else node.attrib['key'])
        if source_node is None:
            continue
        result = Result()
        result.result_id = 'record'+str(index)
        for inner_node in node._children:
            target_node = source_node.find(inner_node.attrib['key'])
            # 有时候没有产生费用的时候会返回不完整的格式，所以这里要检查并跳过
            if target_node is None:
                print("warning:属性%s没有匹配" % inner_node.attrib['key'])
            setattr(result, inner_node.attrib['key'], '' if target_node is None else target_node.text)
        index += 1
        results.append(result)
    return results
